﻿using AntdUI;
using Mapster;
using System.ComponentModel;
using System.Diagnostics;
using WorkTool2.Classes.Data;
using WorkTool2.Entities;
using WorkTool2.Helpers;

namespace WorkTool2.Controls
{
    public partial class History : UserControl
    {
        private Form form;
        private BindingList<HistoryData> _historyTableList;

        public History(Form _form)
        {
            form = _form;
            InitializeComponent();
            table.Columns = [
                new Column("Id", "Id", ColumnAlign.Center).SetVisible(false),
                new Column("Exists", "Exists", ColumnAlign.Center).SetVisible(false),
                new Column("FilePath", "地址", ColumnAlign.Center).SetVisible(false),
                new Column("Source", "来源", ColumnAlign.Center).SetWidth("17%"),
                new Column("FileName", "文件名称", ColumnAlign.Center).SetWidth("25%"),
                new Column("Remark", "备注", ColumnAlign.Center).SetWidth("28%"),
                new Column("CreateTime", "创建时间", ColumnAlign.Center).SetWidth("15%"),
                new Column("Action", "操作", ColumnAlign.Center).SetWidth("15%")
            ];
            Init();
        }

        private void Init()
        {
            var list = SqlSugarHelper.SqliteDb.Queryable<HistoryEntity>().OrderByDescending(x => x.CreateTime).ToList();
            _historyTableList = new BindingList<HistoryData>(list.Adapt<List<HistoryData>>());
            table.Binding(_historyTableList);
        }

        private void table_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            try
            {
                bool? exists = null;
                if (e.Record is HistoryData data)
                {
                    if (!data.Exists)
                    {
                        if (new Modal.Config(form, "失败", "检测到上次操作时文件不存在（已被删除或移动），是否继续操作？", TType.Info)
                        {
                            CancelText = "否",
                            OkType = TTypeMini.Info,
                            OkText = "是"
                        }.open() != DialogResult.OK)
                            return;
                    }
                    if (!File.Exists(data.FilePath))
                    {
                        if (data.Exists)
                            exists = false;
                        new Modal.Config(form, "失败", "文件不存在，请查看文件是否已被删除或移动", TType.Error)
                        {
                            OnButtonStyle = (id, btn) =>
                            {
                                btn.BackExtend = "135, #6253E1, #04BEFE";
                            },
                            CancelText = null,
                            OkText = "知道了"
                        }.open();
                    }
                    else
                    {
                        switch (e.Btn.Id)
                        {
                            case "save":
                                using (SaveFileDialog saveFileDialog = new SaveFileDialog())
                                {
                                    // 设置对话框属性
                                    saveFileDialog.Title = "另存为";
                                    saveFileDialog.Filter = "所有文件 (*.*)|*.*";
                                    saveFileDialog.FilterIndex = 1;
                                    saveFileDialog.FileName = data.FileName;

                                    // 设置初始目录（这里设置为桌面）
                                    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                                    // 其他重要属性
                                    saveFileDialog.OverwritePrompt = true; // 覆盖时提示
                                    saveFileDialog.AddExtension = true;    // 自动添加扩展名
                                    saveFileDialog.RestoreDirectory = true; // 恢复之前的目录
                                    saveFileDialog.ValidateNames = true;   // 验证文件名

                                    // 显示对话框
                                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                                    {
                                        File.Copy(data.FilePath, saveFileDialog.FileName, true);
                                        Notification.success(form, "保存成功", "", AntdUI.TAlignFrom.Top);
                                    }
                                }
                                break;

                            case "open":
                                if (ToolHelper._images.Contains(Path.GetExtension(data.FileName)))
                                {
                                    Preview.open(new Preview.Config(form, Image.FromFile(data.FilePath)));
                                }
                                else
                                {
                                    Process.Start(new ProcessStartInfo
                                    {
                                        FileName = data.FilePath,
                                        UseShellExecute = true
                                    });
                                }
                                break;

                            default:
                                break;
                        }
                        if (!data.Exists)
                            exists = true;
                    }
                    if (exists.HasValue)
                    {
                        data.Exists = exists.Value;
                        (form as Main).UpdateHistoryData(data.Id, exists.Value).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                new Modal.Config(form, "失败", ex.Message, TType.Error)
                {
                    OnButtonStyle = (id, btn) =>
                    {
                        btn.BackExtend = "135, #6253E1, #04BEFE";
                    },
                    CancelText = null,
                    OkText = "知道了"
                }.open();
            }
        }

        private void folder_btn_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", SettingsHelper._fileSettings.SaveFolder);
        }

        private void table_CellClick(object sender, TableClickEventArgs e)
        {
            if (e.Record is HistoryData data)
            {
                if (e.Column.Key == "Remark" && !string.IsNullOrEmpty(data.Remark))
                    Popover.open(new Popover.Config(table, data.Remark) { Offset = e.Rect });
            }
        }
    }
}